package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	order "order_server/proto"
)

type OrderHandler func(ctx context.Context, client order.OrderClient) (interface{}, error)

func OrderClient(ctx context.Context, handler OrderHandler) (interface{}, error) {
	dial, err := grpc.Dial(fmt.Sprintf("%s:%d", "127.0.0.1", 9996), grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := order.NewOrderClient(dial)
	return handler(ctx, client)
}

func OrderCreate(ctx context.Context, in *order.OrderCreateRequest) (*order.OrderCreateResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, client order.OrderClient) (interface{}, error) {
		res, err := client.OrderCreate(ctx, in)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.OrderCreateResponse), nil
}

func OrderUpdatePaid(ctx context.Context, in *order.OrderUpdatePaidRequest) (*order.OrderUpdatePaidResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, client order.OrderClient) (interface{}, error) {
		res, err := client.OrderUpdatePaid(ctx, in)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.OrderUpdatePaidResponse), nil
}

func OrderList(ctx context.Context, in *order.OrderListRequest) (*order.OrderListResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, client order.OrderClient) (interface{}, error) {
		res, err := client.OrderList(ctx, in)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.OrderListResponse), nil
}

func OrderDetail(ctx context.Context, in *order.OrderDetailRequest) (*order.OrderDetailResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, client order.OrderClient) (interface{}, error) {
		res, err := client.OrderDetail(ctx, in)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.OrderDetailResponse), nil
}
